from models.book import Book
from util.log import Log
from util.redis import Redis
from common.const import BaseConstant

async def createBook(book: dict):
    try:
        book = await Book.create(**book)
        return book
    except Exception as e:
        raise e
    
async def allShortUriList():
    try:
        uriList = await Book.all().values("short_uri")
        return uriList
    except Exception as e:
        raise e

async def getBookListByRepositoryId(repositoryId: int):
    try:
        bookList = await Book.filter(repository_id=repositoryId, del_flag=False)
        return bookList
    except Exception as e:
        raise e

async def getBookById(bookId: int):
    try:
        book = await Book.filter(id=bookId, del_flag=False).first()
        return book
    except Exception as e:
        raise e

'''
通过 id 更新 book
'''
async def updateBookById(bookId: int, book: dict):
    try:
        cnt = await Book.filter(id=bookId, del_flag=False).update(**book)
        return cnt
    except Exception as e:
        raise e

'''
通过 shortUri 从 回收站 恢复 book
'''
async def recoverRecycleBook(shortUri: str):
    try:
        res = await Book.filter(short_uri=shortUri).update(**{
            "del_flag": False
        })
        return res
    except Exception as e:
        raise e

'''
通过 shortUri 获取回收站的 book
'''
async def getRecycleBookByShortUri(shortUri: str):
    try:
        book = await Book.filter(short_uri=shortUri, del_flag=True).first()
        return book
    except Exception as e:
        raise e


'''
通过 book_id 删除 book（逻辑删除）
'''
async def deleteBookById(bookId: int):
    try:
        cnt = await Book.filter(id=bookId, del_flag=False).update(**{
            "del_flag": True
        })
        return cnt
    except Exception as e:
        raise e

'''
当用户拖动节点时，更新节点之间的顺序
'''
from tortoise.expressions import F
BEFORE = 'before'
AFTER = 'after'
INNER = 'inner'
async def updateBookWhenDropNode(dropBook: Book, toBook: Book, place: str):
    try:
        cnt = 0
        if place == BEFORE:
            cnt = await Book.filter(parent_id=toBook.parent_id, sort_order__gte=toBook.sort_order, del_flag=False).update(sort_order=F("sort_order") + 1)
        elif place == AFTER:
            cnt = await Book.filter(parent_id=toBook.parent_id, sort_order__gte=toBook.sort_order + 2, del_flag=False).update(sort_order=F("sort_order") + 1)
        elif place == INNER:
            cnt = await Book.filter(parent_id=toBook.parent_id, sort_order__gte=0, del_flag=False).update(sort_order=F("sort_order") + 1)
        return cnt
    except Exception as e:
        raise e

'''
通过 book 的 short_uri 获取 book
'''
async def getBookByShortUri(shortUri: str):
    try:
        book = await Book.filter(short_uri=shortUri, del_flag=False).first()
        return book
    except Exception as e:
        raise e

'''
通过 repositoryIdList 获取删除的 book
'''
async def getRecycleBookListByRepositoryIdList(repositoryIdList: list):
    try:
        res = await Book.filter(repository_id__in=repositoryIdList, del_flag=True).all()
        return res
    except Exception as e:
        raise e
    
'''
获取最近编辑的文档
'''
async def getRecentEditBookListByRepositoryId(repositoryId: int, limit: int):
    try:
        res = await Book.filter(repository_id=repositoryId, del_flag=False).all().order_by("-update_time").limit(limit)
        return res
    except Exception as e:
        raise e

